﻿namespace BuildConfiguratorNS
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using System.Reflection;
    using System.ServiceProcess;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;

    /// <summary>
    /// configuration file creation is done 
    /// </summary>
    public class BuildConfigurator
    {
        static string wrkDire;
        static FileInfo fI;
        static StreamWriter oDDF;


        /// <summary>
        /// Deletes a particular project configuration
        /// from the ccnet project file.
        /// </summary>
        /// <param name="ccnetProjectName">name of the project to be deleted</param>
        public static void DeleteBuildConfiguration(string ccnetProjectName)
        {
            XDocument ccnetConfig = XDocument.Load(@"C:\Program Files\CruiseControl.NET\server\ccnet.config");

            // If the project is already present, remove it.
            IEnumerable<XElement> projects = ccnetConfig.Root.Elements("project");
            foreach (XElement proj in projects)
            {
                if (proj.Element("name").Value == ccnetProjectName)
                {
                    proj.Remove();
                    break;
                }
            }

            // Save the ccnet.config
            ccnetConfig.Save(@"C:\Program Files\CruiseControl.NET\server\ccnet.config");
        }

        /// <summary>
        /// Save the configuration of a single project.
        /// </summary>
        /// <param name="buildParameters">Build configuration of a particular project</param>
        public static void SaveBuildConfiguration(BuildParameters buildParameters)
        {
            bool IsTrigger=false;
            
            XDocument ccnetConfig = XDocument.Load(@"C:\Program Files\CruiseControl.NET\server\ccnet.config");

            // If the project is already present, remove it.
            IEnumerable<XElement> projects = ccnetConfig.Root.Elements("project");
            foreach (XElement proj in projects)
            {
                if (proj.Element("name").Value == buildParameters.GeneralSettings.CCnetProjectName)
                {
                    proj.Remove();
                    break;
                }
            }

            // Create svn task element
            XElement sourcecontrol = null;
            if (buildParameters.SourceControlSettings.SourceType == "svn" || buildParameters.SourceControlSettings.SourceType==null)
            {
                try
                {
                
                    wrkDire = buildParameters.GeneralSettings.TargetPath + @"\Buildroot_" + buildParameters.GeneralSettings.CCnetProjectName + @"\src";
                }
                catch (Exception e1)
                {
                    wrkDire =  buildParameters.GeneralSettings.TargetPath + @"\Buildroot_" + buildParameters.GeneralSettings.CCnetProjectName + @"\src";
                }

                sourcecontrol = new XElement(
                            "sourcecontrol",
                                new XAttribute("type", "svn"),
                                new XElement("trunkUrl", buildParameters.SourceControlSettings.TrunkUrl),
                                new XElement("workingDirectory", wrkDire),
                                new XElement("executable", @"c:\program files\subversion\bin\svn.exe"),
                                new XElement("username", buildParameters.SourceControlSettings.UserName),
                                new XElement("password", buildParameters.SourceControlSettings.Password),
                                new XElement("autoGetSource", buildParameters.SourceControlSettings.AutoGetSource.ToLower(CultureInfo.InvariantCulture)),
                                new XComment("If you are tagging a copy on success, you should give the <tagBaseUrl>"),
                                new XElement("tagOnSuccess", buildParameters.SourceControlSettings.TagOnSuccess.ToLower(CultureInfo.InvariantCulture)),
                                new XElement("tagBaseUrl", buildParameters.SourceControlSettings.TagBaseUrl),
                                new XElement("timeout", buildParameters.SourceControlSettings.Timeout));
            }

            else if (buildParameters.SourceControlSettings.SourceType == "vsts")
            {
                try
                {
                    wrkDire =  buildParameters.GeneralSettings.TargetPath + @"\Buildroot_" + buildParameters.GeneralSettings.CCnetProjectName + @"\src" ;
                }
                catch (Exception e1)
                {
                    wrkDire =  buildParameters.GeneralSettings.TargetPath + @"\Buildroot_" + buildParameters.GeneralSettings.CCnetProjectName + @"\src";
                }
                sourcecontrol = new XElement(
                            "sourcecontrol",
                                new XAttribute("type", "vsts"),
                                new XAttribute("autoGetSource", buildParameters.SourceControlSettings.AutoGetSource.ToLower(CultureInfo.InvariantCulture)),
                                new XAttribute("applyLabel",buildParameters.SourceControlSettings.TagOnSuccess.ToLower(CultureInfo.InvariantCulture)),
                                new XElement("server", buildParameters.SourceControlSettings.TrunkUrl),
                                new XElement("username", buildParameters.SourceControlSettings.UserName),
                                new XElement("password", buildParameters.SourceControlSettings.Password),
                                new XElement("project", buildParameters.SourceControlSettings.Vstsproject),
                                new XElement("workingDirectory", wrkDire));
            }

            else if (buildParameters.SourceControlSettings.SourceType == "clearCase")
            {
                try
                {
                    //wrkDire = buildParameters.CompileSettings.SolutionFile.Substring(0, (buildParameters.CompileSettings.SolutionFile.IndexOf(@"\")));
                    wrkDire = buildParameters.GeneralSettings.TargetPath + @"\Buildroot_" + buildParameters.GeneralSettings.CCnetProjectName + @"\src";
                }
                catch (Exception e1)
                {
                    wrkDire = buildParameters.GeneralSettings.TargetPath + @"\Buildroot_" + buildParameters.GeneralSettings.CCnetProjectName + @"\src";
                }
                sourcecontrol = new XElement(
                            "sourcecontrol",
                                new XAttribute("type", "clearCase"),
                                new XElement("viewPath", buildParameters.SourceControlSettings.CcViewPath),
                                new XElement("branch", buildParameters.SourceControlSettings.CCBranch),
                                new XElement("autoGetSource", buildParameters.SourceControlSettings.AutoGetSource.ToLower(CultureInfo.InvariantCulture)),
                                new XElement("useLabel", buildParameters.SourceControlSettings.TagOnSuccess.ToLower(CultureInfo.InvariantCulture)),
                                new XElement("useBaseline", buildParameters.SourceControlSettings.IsCCBaseLine.ToLower(CultureInfo.InvariantCulture)),
                                new XElement("projectVobName", buildParameters.SourceControlSettings.CCProjectVob),
                                new XElement("viewName", buildParameters.SourceControlSettings.CcViewName),
                                new XElement("viewName", "cleartool"),
                                new XElement("timeout", buildParameters.SourceControlSettings.Timeout));
            }

                XElement intervaltrigger = null;

            if (buildParameters.TriggerSettings.EnableTrigger)
            { 
                IsTrigger=true;
                intervaltrigger=new XElement ("intervalTrigger",
                                          new XAttribute("seconds", buildParameters.TriggerSettings.TriggerInterval),
                                          new XAttribute("buildCondition", buildParameters.TriggerSettings.BuildCondition));                
            }
            
            XElement schTrigger = null;
            if (buildParameters.ScheduleTriggerSetting.EnablescheduleTrigger)
            {
                IsTrigger = true;
                XElement _WeekDays = null;
                if (buildParameters.ScheduleTriggerSetting.WeekDays != string.Empty)
                {
                    string[] weekdayList = buildParameters.ScheduleTriggerSetting.WeekDays.Split(new char[] {';'},StringSplitOptions.RemoveEmptyEntries);
                    _WeekDays = new XElement("weekDays");
                    foreach (string weekday in weekdayList)
                    {
                        XElement _weekday = new XElement("weekDay", weekday);
                        _WeekDays.Add(_weekday);
                    }
                    
                }


                schTrigger = new XElement("scheduleTrigger",
                                        new XAttribute("time", buildParameters.ScheduleTriggerSetting.TriggerIntervalTime),
                                        new XAttribute("buildCondition", buildParameters.ScheduleTriggerSetting.BuildCondition),
                                        _WeekDays);                                    
                                    
            }
            XElement filTRigger = null;
            if (buildParameters.FilterTriggerSetting.EnableFilterTrigger)
            {
                IsTrigger = true;
                filTRigger = new XElement("filterTrigger",
                                new XAttribute("startTime",buildParameters.FilterTriggerSetting.StartTime),
                                new XAttribute("endTime",buildParameters.FilterTriggerSetting.EndTime),
                                new XElement("trigger",
                                        new XAttribute("type","intervalTrigger"),
                                        new XAttribute("seconds",buildParameters.FilterTriggerSetting.DuratinoSecs)));                                
            }


            XElement triggers = null;
            //if (string.Compare(buildParameters.TriggerSettings.EnableTrigger.ToString(), "true", StringComparison.OrdinalIgnoreCase) == 0)
            if (IsTrigger)
            {
                triggers = new XElement(
                                "triggers", intervaltrigger, schTrigger,filTRigger);
            }


            //Create the Email task element            
            XElement xEleUsers = new XElement("users");
            char[] delimiterChars = { ';' };
            string[] tousers = buildParameters.EmailSettings.ToAddresses.Split(delimiterChars,StringSplitOptions.RemoveEmptyEntries);
            foreach (string s1 in tousers)
            {
                XElement user = new XElement("user",
                                        new XAttribute("name", s1.Substring(0,s1.IndexOf('@'))),
                                        new XAttribute("group", "buildmaster"),
                                        new XAttribute("address", s1));
                xEleUsers.Add(user);
            }
            XElement mailTask = new XElement(
                                        "email",
                            new XAttribute("from", buildParameters.EmailSettings.FromAddresses),
                            new XAttribute("mailhost", buildParameters.EmailSettings.SmtpServer),
                            new XAttribute("includeDetails", "TRUE"),
                            new XElement(xEleUsers),
                            new XElement(
                                "groups",
                                    new XElement(
                                        "group",
                                        new XAttribute("name", "buildmaster"),
                                        new XAttribute("notification", "always"))));

            XElement eleTask=new XElement(
                    "tasks",
                    new XElement(
                            "msbuild",
                                new XElement("executable", @"C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe"),
                                new XElement("workingDirectory",  buildParameters.GeneralSettings.TargetPath + @"\Buildroot_" + buildParameters.GeneralSettings.CCnetProjectName),
                                new XElement("projectFile", "build.proj"),
                                new XElement("buildArgs", "/noconsolelogger /p:Configuration=Debug /v:diag"),
                                new XElement("targets", "BuildAll"),
                                new XComment("Time out the build if it is not getting completed in an hour"),
                                new XElement("timeout", buildParameters.CompileSettings.BuildTimeout),
                                new XElement("logger", @"C:\Program Files\CruiseControl.NET\server\ThoughtWorks.CruiseControl.MsBuild.dll")));          
                
            
            //publisher task implementation
            XElement publistsk = new XElement(
                    "publishers",
                    new XElement(
                        "merge",
                        new XElement(
                            "files",
                            new XElement("file",  buildParameters.GeneralSettings.TargetPath + @"\Buildroot_" + buildParameters.GeneralSettings.CCnetProjectName + @"\buildlogs\Latest\*.xml"),
                            new XElement("file",  buildParameters.GeneralSettings.TargetPath + @"\Buildroot_" + buildParameters.GeneralSettings.CCnetProjectName + @"\buildlogs\Latest\*.trx"),
                            new XElement("file",  buildParameters.GeneralSettings.TargetPath + @"\Buildroot_" + buildParameters.GeneralSettings.CCnetProjectName + @"\buildlogs\Latest\NDependOut\*.xml"))),
                    new XElement(
                        "xmllogger",
                        new XElement("logDir",  buildParameters.GeneralSettings.TargetPath + @"\Buildroot_" + buildParameters.GeneralSettings.CCnetProjectName + @"\buildlogs\Latest\log")));

            
            // Add Email task under tasks list only if EmailOption enabled

            if (buildParameters.EmailSettings.EnableEmail == true)
            {
                publistsk.Add(new XElement(mailTask));
            }

            XElement exterLink = null;
            if (buildParameters.MSCodeCoverageSettings.EnableMSCodeCoverage)
            {
                string rptfile=  buildParameters.MSCodeCoverageSettings.CoverageOutputFile.Substring(0,buildParameters.MSCodeCoverageSettings.CoverageOutputFile.IndexOf('.'));
                string xmlfle = buildParameters.GeneralSettings.TargetPath + "\\buildroot_" + buildParameters.GeneralSettings.CCnetProjectName + "\\buildlogs\\Latest\\" + rptfile + ".xml";
;
                string exLink = buildParameters.MSCodeCoverageSettings.MscovRepLink + "?rptLink=" + xmlfle + "&projName=" + buildParameters.GeneralSettings.CCnetProjectName;
                exterLink = new XElement(
                    "externalLinks",
                    new XElement(
                        "externalLink",
                        new XAttribute("name", "MS Coverage Report Link"),
                        new XAttribute("url", exLink)));

            }


            
            
            // Create the "project" tree.
            XElement project = new XElement(
                "project", 				
                new XElement("name", buildParameters.GeneralSettings.CCnetProjectName),				
				new XElement("modificationDelaySeconds",buildParameters.CompileSettings.CheckinWaitingTime),
                sourcecontrol, triggers, eleTask, publistsk, exterLink
                );

			
            // Add the project to the root element "cruisecontrol"
            ccnetConfig.Root.Add(project);

            // Create necessary folder structures for the current project
			AddProjectFolders(buildParameters.GeneralSettings.CCnetProjectName, buildParameters.GeneralSettings.TargetPath);

            //// Write the build script file as per the user inputs
            CreateMSBuildScriptFile(buildParameters);

            // Save the ccnet.config
            ccnetConfig.Save(@"C:\Program Files\CruiseControl.NET\server\ccnet.config");
            UpdateCCNetDashboard();
        }


        /// <summary>
        /// This method will create the build script file 
        /// accoring to the build settings
        /// </summary>
        /// <param name="buildParameters">structure carries the build settings</param>
        public static void CreateMSBuildScriptFile(BuildParameters buildParameters)
        {
            // Get the executing assembly and read the embedded Targets.xml file
            Assembly asm = Assembly.GetExecutingAssembly();
            TextReader textReader = new StreamReader(asm.GetManifestResourceStream("BuildConfigurator.BuildTargets.Targets.xml"));

            XDocument buildConfigTargets = XDocument.Load(textReader);
            textReader.Close();

            // Declare the default namespace for the document
            XNamespace defaultns = "http://schemas.microsoft.com/developer/msbuild/2003";

            XComment scriptDocumentation = new XComment(@"
                                      It is recommented that editing of this file is to be done
                                      only to the properties set in this file. There are some
                                      properties which has to be editted for making a new proj-
                                      ect configured with the help of this file. These include
                                  
                                  1.  If the version of the tools used are different then the 
                                      properties belonging to those tools and the installation 
                                      paths has to be updated.
                                     
                                  2.  For changing the assembly version, the properties such
                                      as <Major>, <Minor> etc has to be modified.
                                      
                                  3.  If you want the build logs to be generated at a diferent
                                      folder, modify the <BuildLogsDirectory> path.
                                      
                                  4.  Modify the SVN trunk uri to reflect the actual uri of 
                                      your project.
                                      
                                  5.  If more than one assembly info is to be produced, 
                                      uncomment the <AssemblyInfo> tag and use it accordingly
                                      
                                  6.  To change the build configuration between Debug and 
                                      Release, modify the <BuildConfiguration> property.");

			XElement common = new XElement(
							defaultns + "PropertyGroup",
							new XElement(defaultns + "Common"),
							new XElement(defaultns + "DOUBLE_QUOTES", "%22"),
							new XElement(defaultns + "BuildConfiguration", buildParameters.CompileSettings.BuildConfiguration),
							new XElement(defaultns + "BuildRoot", buildParameters.GeneralSettings.TargetPath + @"\Buildroot_" + buildParameters.GeneralSettings.CCnetProjectName),
							new XElement(defaultns + "BuildDirectory", @"$(Buildroot)\bin"),
							new XElement(defaultns + "BuildLogsDirectory", @"$(BuildRoot)\buildlogs"),
							new XElement(defaultns + "BuildSourceDirectory", @"$(BuildRoot)\src"),
							new XElement(defaultns + "BuildSettingsDirectory", @"$(BuildRoot)\BuildSettings"),
							new XElement(defaultns + "MainSolutionFile", buildParameters.CompileSettings.SolutionFile),
							new XElement(defaultns + "DevEnvPath", buildParameters.GeneralSettings.DevEnvPath));
            XElement prescript = new XElement(
                            defaultns + "PropertyGroup",
                            new XElement(defaultns + "PreScript"),
                            new XElement(defaultns + "EnablePreScriptTask", buildParameters.PreScriptSettings.EnablePreScript.ToString().ToLower(CultureInfo.InvariantCulture)),
                            new XElement(defaultns + "PreScriptFile", buildParameters.PreScriptSettings.PreScriptFile));
            XElement version = new XElement(
                            defaultns + "PropertyGroup",
                            new XElement(defaultns + "Version"),
                            new XElement(defaultns + "EnableVersionTask", buildParameters.VersioningSettings.EnableVersion.ToString().ToLower(CultureInfo.InvariantCulture)),
                            new XElement(defaultns + "Major", buildParameters.VersioningSettings.MajorVersion),
                            new XElement(defaultns + "Minor", buildParameters.VersioningSettings.MinorVersion),
                            new XElement(defaultns + "Build", buildParameters.VersioningSettings.Build),
                            new XElement(defaultns + "Revision", buildParameters.VersioningSettings.Revision));
            XElement styleCop = new XElement(
                            defaultns + "PropertyGroup",
                            new XElement(defaultns + "StyleCop"),
                            new XElement(defaultns + "EnableStyleCopTask", buildParameters.StyleCopSettings.EnableStyleCop.ToString().ToLower(CultureInfo.InvariantCulture)),
                            new XElement(defaultns + "StyleCopTaskAssembly", @"C:\program Files\MSBuild\Microsoft\StyleCop\v4.3\Microsoft.StyleCop.dll"),
                            new XElement(defaultns + "StyleCopReportFile", "StyleCopViolations.xml"),
                            new XElement(defaultns + "StyleCopCustomSettingsFile", buildParameters.StyleCopSettings.StyleCopCustomSettingsFile));

			XElement nunit;
			if (buildParameters.NUnitSettings != null)
			{
				nunit = new XElement(
								defaultns + "PropertyGroup",
								new XElement(defaultns + "NUnit"),
								new XElement(defaultns + "EnableNUnitTask", buildParameters.NUnitSettings.EnableNUnit.ToString().ToLower(CultureInfo.InvariantCulture)),								
								new XElement(defaultns + "NUnitReportFile", buildParameters.NUnitSettings.NUnitReportFile),
								new XElement(defaultns + "NUnitDLLName", buildParameters.NUnitSettings.NUnitDLLName),
								new XElement(defaultns + "NUnitInstallDirectory",buildParameters.NUnitSettings.NUnitEXEPath ));

			}
			else
			{
				nunit = new XElement(
								defaultns + "PropertyGroup",
								new XElement(defaultns + "NUnit"),
								new XElement(defaultns + "EnableNUnitTask", "False"),								
								new XElement(defaultns + "NUnitReportFile", ""),
								new XElement(defaultns + "NUnitDLLName", ""),
								new XElement(defaultns + "NUnitInstallDirectory", ""));
			}

            XElement ncover = new XElement(
                            defaultns + "PropertyGroup",
                            new XElement(defaultns + "NCover"),
                            new XElement(defaultns + "EnableNCoverTask", buildParameters.NCoverSettings.EnableNCover.ToString().ToLower(CultureInfo.InvariantCulture)),
                            new XElement(defaultns + "NCoverExe", @"$(DOUBLE_QUOTES)C:\Program Files\NCover\NCover.Console.exe$(DOUBLE_QUOTES)"),
                            new XElement(defaultns + "CoverageLogFile", buildParameters.NCoverSettings.NCoverLogFile),
                            new XElement(defaultns + "CoverageReportFile", "coverage.xml"),
                            new XElement(defaultns + "AppToProfileExe", @"$(DOUBLE_QUOTES)$(NUnitInstallDirectory)\nunit-console.exe$(DOUBLE_QUOTES)"));
            
            XElement mscodecoverage = new XElement(
                            defaultns + "PropertyGroup",
                            new XElement(defaultns + "MSCodeCoverage"),
                            new XElement(defaultns + "EnableMSCodeCoverage", buildParameters.MSCodeCoverageSettings.EnableMSCodeCoverage.ToString().ToString(CultureInfo.InvariantCulture)),
                            new XElement(defaultns + "InstrExePath",buildParameters.MSCodeCoverageSettings.InstrExePath),
                            new XElement(defaultns + "PerfCmdExePath",buildParameters.MSCodeCoverageSettings.PerfCmdExePath),
                            new XElement(defaultns + "MStestExePath",buildParameters.MSCodeCoverageSettings.MsTestExePath),
                            new XElement(defaultns + "Instrbinaries",buildParameters.MSCodeCoverageSettings.InstrBinaries),
                            new XElement(defaultns + "TestBinary",buildParameters.MSCodeCoverageSettings.TestBinary),
                            new XElement(defaultns + "outputCoverageFileName",buildParameters.MSCodeCoverageSettings.CoverageOutputFile),
                            new XElement(defaultns + "MSCoverageLink",buildParameters.MSCodeCoverageSettings.MscovRepLink));


            XElement fxcop = new XElement(
                            defaultns + "PropertyGroup",
                            new XElement(defaultns + "FxCop"),
                            new XElement(defaultns + "EnableFxCopTask", buildParameters.FxCopSettings.EnableFxCop.ToString().ToLower(CultureInfo.InvariantCulture)),
                            new XElement(defaultns + "FxCopResultsFile", buildParameters.FxCopSettings.FxCopReportFile),
                            new XElement(defaultns + "FxCopInstallDirectory", @"C:\Program Files\Microsoft FxCop 1.36"),
                            new XElement(defaultns + "FxCopProjectFile", buildParameters.FxCopSettings.FxCopProjectFile));

            XElement catnet = new XElement(
                            defaultns + "PropertyGroup",
                            new XElement(defaultns + "CatNet"),
                            new XElement(defaultns + "EnableCatNet", buildParameters.CatNetSettings.EnableCatNet.ToString().ToLower(CultureInfo.InvariantCulture)),
                            new XElement(defaultns + "ScanFiles", buildParameters.CatNetSettings.ScanFiles),
                            new XElement(defaultns + "CNPath", buildParameters.CatNetSettings.CNPath),
                            new XElement(defaultns + "CNRptFileName", buildParameters.CatNetSettings.CNRptFileName));

            XElement sandcastleHFB = new XElement(
                            defaultns + "PropertyGroup",
                            new XElement(defaultns + "SandCastleHFB"),
                            new XElement(defaultns + "EnableSandCastleHFBTask", buildParameters.SandcastleHelpFileBuilderSettings.EnableSandcastleHelpFileBuilder.ToString().ToLower(CultureInfo.InvariantCulture)),
                            new XElement(defaultns + "SandCastleHFBProject", buildParameters.SandcastleHelpFileBuilderSettings.SandcastleHelpFileBuilderProjectFile),
                            new XElement(defaultns + "SandCastleHFBExe", @"C:\Program Files\EWSoftware\Sandcastle Help File Builder\SandcastleBuilderConsole.exe"),
                            new XElement(defaultns + "SandCastleOutputFolderName", buildParameters.SandcastleHelpFileBuilderSettings.SandcastleHelpFileBuilderOutputDirectory));
            XElement ndepend = new XElement(
                            defaultns + "PropertyGroup",
                            new XElement(defaultns + "NDepend"),
                            new XElement(defaultns + "EnableNDependTask", buildParameters.NDependSettings.EnableNDepend.ToString().ToLower(CultureInfo.InvariantCulture)),
                            new XElement(defaultns + "NDependProjectFile", buildParameters.NDependSettings.NDependProjectFile),
                            new XElement(defaultns + "NDependExe", @"C:\Program Files\NDepend\NDepend.Console.exe"),
                            new XElement(defaultns + "NDependReportDirectory", buildParameters.NDependSettings.NDependReportDirectory));
            XElement database = new XElement(
                            defaultns + "PropertyGroup",
                            new XElement(defaultns + "Database"),
                            new XElement(defaultns + "EnableDatabaseTask", buildParameters.DatabaseSettings.EnableDatabase.ToString().ToLower(CultureInfo.InvariantCulture)),
                            new XElement(defaultns + "dbserver", buildParameters.DatabaseSettings.DBServerName),
                            new XElement(defaultns + "dbuser", buildParameters.DatabaseSettings.DBLogin),
                            new XElement(defaultns + "dbpassword", buildParameters.DatabaseSettings.DBPassword),
                            new XElement(defaultns + "dbname", buildParameters.DatabaseSettings.DBName),
                            new XElement(defaultns + "SqlInstallationPath", @"C:\Program Files\Microsoft SQL Server\90\Tools\Binn\"),
                            new XElement(defaultns + "CreateDbSqlFile", @"$(BuildSettingsDirectory)\Database\createDB.sql"),
                            new XElement(defaultns + "DbTablesSqlDirectory", @"$(BuildSettingsDirectory)\Database\Tables"),
                            new XElement(defaultns + "DbViewsSqlDirectory", @"$(BuildSettingsDirectory)\Database\Views"),
                            new XElement(defaultns + "DbStoredProcsSqlDirectory", @"$(BuildSettingsDirectory)\Database\StoredProcedures"));
            XElement email = new XElement(
                            defaultns + "PropertyGroup",
                            new XElement(defaultns + "Email"),
                            new XElement(defaultns + "EnableEmailTask", "false"),
                            new XElement(defaultns + "SmtpServer", buildParameters.EmailSettings.SmtpServer),
                            new XElement(defaultns + "ToAddresses", buildParameters.EmailSettings.ToAddresses),
                            new XElement(defaultns + "FromAddresses", buildParameters.EmailSettings.FromAddresses));                            
            XElement postscript = new XElement(
                            defaultns + "PropertyGroup",
                            new XElement(defaultns + "PostScript"),
                            new XElement(defaultns + "EnablePostScriptTask", buildParameters.PostScriptSettings.EnablePostScript.ToString().ToLower(CultureInfo.InvariantCulture)),
                            new XElement(defaultns + "PostScriptFile", buildParameters.PostScriptSettings.PostScriptFile));

			XElement mstest; 
			if (buildParameters.MSTestSettings != null)
			{
				mstest = new XElement(
								defaultns + "PropertyGroup",
								new XElement(defaultns + "MSTest"),
								new XElement(defaultns + "EnableMstestTask", buildParameters.MSTestSettings.EnableMstestTask.ToString().ToLower(CultureInfo.InvariantCulture)),
								new XElement(defaultns + "MStestExe", buildParameters.MSTestSettings.MstestExe),
								new XElement(defaultns + "MSTestDll", buildParameters.MSTestSettings.MstestDll),
								new XElement(defaultns + "MSTestOutPut", buildParameters.MSTestSettings.Mstestoutput));
			}
			else
			{
				mstest = new XElement(
								defaultns + "PropertyGroup",
								new XElement(defaultns + "MSTest"),
								new XElement(defaultns + "EnableMstestTask", "False"),
								new XElement(defaultns + "MStestExe", ""),
								new XElement(defaultns + "MSTestDll", ""),
								new XElement(defaultns + "MSTestOutPut", ""));
			}
			XElement postcompilescript = new XElement(
							defaultns + "PropertyGroup",
							new XElement(defaultns + "PostCompile"),
							new XElement(defaultns + "EnablePostCompile", buildParameters.PostScriptSettings.EnablePostCompile.ToString().ToLower(CultureInfo.InvariantCulture)),
							new XElement(defaultns + "PostCompileFile", buildParameters.PostScriptSettings.PostCompileScriptFile));

			XElement postdeployscript = new XElement(
							defaultns + "PropertyGroup",
							new XElement(defaultns + "PostDeploy"),
							new XElement(defaultns + "EnablePostDeploy", buildParameters.PostScriptSettings.EnablePostDeploy.ToString().ToLower(CultureInfo.InvariantCulture)),
							new XElement(defaultns + "PostDeployFile", buildParameters.PostScriptSettings.PostDeployScriptFile));

			XElement iisscript = new XElement(
							defaultns + "PropertyGroup",
							new XElement(defaultns + "IISConfig"),
							new XElement(defaultns + "EnableIIS", buildParameters.IISSettings.EnableIIS),
							new XElement(defaultns + "IISType", buildParameters.IISSettings.IISType),
							new XElement(defaultns + "Server", buildParameters.IISSettings.WebServerName),
							new XElement(defaultns + "AppPoolName", buildParameters.IISSettings.ApplicationPoolName),
							new XElement(defaultns + "VdirName", buildParameters.IISSettings.VirtualDirectoryName),
							new XElement(defaultns + "VdirPhyPath", buildParameters.IISSettings.PhysicalDirectoryPath),
							new XElement(defaultns + "WebProjLocation", buildParameters.IISSettings.WebProjectPath),
                            new XElement(defaultns + "ProdDeployLoc", buildParameters.IISSettings.ProductionServerLocation),
                            new XElement(defaultns + "QADeployLoc", buildParameters.IISSettings.QAServerLocation),
                            new XElement(defaultns + "DevDeployLoc", buildParameters.IISSettings.DevelopmentServerLocation));



						//new XElement(defaultns + "EnableWSPCreation", buildParameters.MossWSPCreation[0].EnableWSPCreation));
                     

            //XElement temp = null;
            
            //}
            //XElement WspCreationScript = new XElement(
            //    defaultns + "Target",
            //        new XAttribute("Name", "WspCreationExe"), temp);                


            

            //XElement WSPCreationScript = new XElement(
            //            defaultns + "PropertyGroup",
            //            new XElement(defaultns + "WSPCreation"),
            //            new XElement(defaultns + "EnableWSPCreation", buildParameters.MossWSPCreation.EnableWSPCreation.ToString().ToLower(CultureInfo.InvariantCulture)),
            //            new XElement(defaultns + "DDFileName", buildParameters.MossWSPCreation.DDFileName),
            //            new XElement(defaultns + "ManifestRelativeFileName", buildParameters.MossWSPCreation.ManifestRelativeFileName),
            //            new XElement(defaultns + "DDLPath", buildParameters.MossWSPCreation.DDLPath),
            //            new XElement(defaultns + "OutputDDLPath", buildParameters.MossWSPCreation.OutputDDLPath),
            //            new XElement(defaultns + "GACPath", buildParameters.MossWSPCreation.GACPath),
            //            new XElement(defaultns + "OutputGACPath", buildParameters.MossWSPCreation.OutputGACPath),
            //            new XElement(defaultns + "FeaturePath", buildParameters.MossWSPCreation.FeaturePath),
            //            new XElement(defaultns + "OutputFeaturePath", buildParameters.MossWSPCreation.OutputFeaturePath),
            //            new XElement(defaultns + "ResourcePath", buildParameters.MossWSPCreation.ResourcePath),
            //            new XElement(defaultns + "OutputResourcePath", buildParameters.MossWSPCreation.OutputResourcePath),
            //            new XElement(defaultns + "ImagePath", buildParameters.MossWSPCreation.ImagePath),
            //            new XElement(defaultns + "OutputImagePath", buildParameters.MossWSPCreation.OutputImagePath),
            //            new XElement(defaultns + "LayoutPath", buildParameters.MossWSPCreation.LayoutPath),
            //            new XElement(defaultns + "OutputLayoutPath", buildParameters.MossWSPCreation.OutputLayoutPath),
            //            new XElement(defaultns + "ThemePath", buildParameters.MossWSPCreation.ThemePath),
            //            new XElement(defaultns + "OutputThemePath", buildParameters.MossWSPCreation.OutputThemePath),
            //            new XElement(defaultns + "Pathfor1033", buildParameters.MossWSPCreation.Pathfor1033),
            //            new XElement(defaultns + "Output1033Path", buildParameters.MossWSPCreation.Output1033Path),
            //            new XElement(defaultns + "SiteTemplatePath", buildParameters.MossWSPCreation.SiteTemplatePath),
            //            new XElement(defaultns + "OutputSiteTemplatePath", buildParameters.MossWSPCreation.OutputSiteTemplatePath),
            //            new XElement(defaultns + "XMLPath", buildParameters.MossWSPCreation.XMLPath),
            //            new XElement(defaultns + "OutputXMLPath", buildParameters.MossWSPCreation.OutputXMLPath),
            //            new XElement(defaultns + "ControlTemplatePath", buildParameters.MossWSPCreation.ControlTemplatePath),
            //            new XElement(defaultns + "OutputControlTemplatePath", buildParameters.MossWSPCreation.OutputControlTemplatePath),
            //            new XElement(defaultns + "TemplatePath", buildParameters.MossWSPCreation.TemplatePath),
            //            new XElement(defaultns + "WSPLocation", buildParameters.MossWSPCreation.WSPLocation));
			
            // Creating the main script document.
            XDocument buildConfig =
                new XDocument(
                    new XDeclaration("1.0", "utf-8", null),
                    new XElement(
                        defaultns + "Project",
                        new XAttribute("DefaultTargets", "BuildAll"),
                        new XAttribute(@"xmlns", @"http://schemas.microsoft.com/developer/msbuild/2003"),
                        new XElement(
                            defaultns + "Import", new XAttribute("Project", @"$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets")),
                        scriptDocumentation,
                        new XComment("          Common Properties         "),
                        common,
                        new XComment("          Pre-Script Properties         "),
                        prescript,
                        new XComment("          Versioning Properties         "),
                        version,
                        new XComment("          StyleCop Properties         "),
                        styleCop,
                        new XComment("             NUnit Properties          "),
                        nunit,
                        new XComment("          NCover Properties        "),
                        ncover,
                        new XComment("          MS Code Coverage Properties        "),
                        mscodecoverage,
                        new XComment("          FxCop Properties         "),
                        fxcop,
						new XComment("			CATNET Properties		"),
						catnet,
                        new XComment("          SandCastleHFB Properties         "),
                        sandcastleHFB,
                        new XComment("          NDepend Properties         "),
                        ndepend,
                        new XComment("          Database Properties         "),
                        database,
                        new XComment("          Email Properties         "),
                        email,
                        new XComment("          Post-Script Properties         "),
                        postscript,
                        new XComment("          MSTest Properties         "),
                        mstest,
						new XComment("          Post compile Properties         "),
						postcompilescript,
						new XComment("          Post Deploy Properties         "),
						postdeployscript,
						new XComment ("          IIS Config Properties         "),
                        iisscript));
            
           MSCovScriptCreation(buildParameters.GeneralSettings.TargetPath + @"\Buildroot_" + buildParameters.GeneralSettings.CCnetProjectName + @"\BuildSettings", buildParameters.MSCodeCoverageSettings);
            
			
			

            // Add all the targets and ItemGrops from the Targets.xml document
            // to the main document.
            buildConfig.Root.Add(buildConfigTargets.Root.Nodes());

            // Save the script file.
            buildConfig.Save(buildParameters.GeneralSettings.TargetPath + @"\Buildroot_" + buildParameters.GeneralSettings.CCnetProjectName + @"\build.proj");
			
			UpdateTargetDependants(buildParameters);		


        }

        /// <summary>
        /// This method is invoked from the UI to apply
        /// the default build configuration.
        /// </summary>
        public void ApplyDefaultConfiguration()
        {
        
            XDocument ccnetConfig = new XDocument(new XElement("cruisecontrol"));
            ccnetConfig.Save(@"C:\Program Files\CruiseControl.NET\server\ccnet.config");
        
        }
        
        public static void ApplyBuildConfiguration(BuildParameters buildParameters)
        {
            BuildConfigurator.SaveBuildConfiguration(buildParameters);            
        }

        /// <summary>
        /// Creates the build folder structure for the current project
        /// </summary>
        /// <param name="ccnetProjectName">name of the project to be configured</param>
        public static void AddProjectFolders(string ccnetProjectName, string targetPath)
        {
            string buildRootDirectory =  targetPath + @"\Buildroot_" + ccnetProjectName;

            if (!Directory.Exists(buildRootDirectory))
            {
                Directory.CreateDirectory(buildRootDirectory);
            }
            if (!Directory.Exists(buildRootDirectory + @"\bin"))
            {
                Directory.CreateDirectory(buildRootDirectory + @"\bin");
            }
            if (!Directory.Exists(buildRootDirectory + @"\bin\MSCodeCovDir"))
            {
                Directory.CreateDirectory(buildRootDirectory + @"\bin\MSCodeCovDir");
            }
        
            if (!Directory.Exists(buildRootDirectory + @"\buildlogs"))
            {
                Directory.CreateDirectory(buildRootDirectory + @"\buildlogs");
            }

            if (!Directory.Exists(buildRootDirectory + @"\buildlogs\Latest"))
            {
                Directory.CreateDirectory(buildRootDirectory + @"\buildlogs\Latest");
            }
        
            if (!Directory.Exists(buildRootDirectory + @"\src"))
            {
                Directory.CreateDirectory(buildRootDirectory + @"\src");
            }
            //if (!Directory.Exists(buildRootDirectory + @"\src\" + wrkDire))

            if (!Directory.Exists(wrkDire))
            { 
                Directory.CreateDirectory(wrkDire);
            }

            if (!Directory.Exists(buildRootDirectory + @"\BuildSettings" ))
            {
                Directory.CreateDirectory(buildRootDirectory + @"\BuildSettings");
                Assembly asmbly = Assembly.GetExecutingAssembly();
                TextReader fxcpStream = new StreamReader(asmbly.GetManifestResourceStream("BuildConfigurator.BuildTargets.Build.FxCop"));
                XDocument doc = XDocument.Load(fxcpStream);
                doc.Save(buildRootDirectory + @"\BuildSettings\Build.FxCop");
                
                //to load the shfb file in the build settings folder
                fxcpStream = new StreamReader(asmbly.GetManifestResourceStream("BuildConfigurator.BuildTargets.build.shfb"));
                doc = XDocument.Load(fxcpStream);
                doc.Save(buildRootDirectory + @"\BuildSettings\Build.shfb");

                //to load the stylecop file in the build settings folder
                fxcpStream = new StreamReader(asmbly.GetManifestResourceStream("BuildConfigurator.BuildTargets.Settings.StyleCop"));
                doc = XDocument.Load(fxcpStream);
                doc.Save(buildRootDirectory + @"\BuildSettings\Settings.StyleCop");

                //to load the Ndepend file in the build settings folder
                fxcpStream = new StreamReader(asmbly.GetManifestResourceStream("BuildConfigurator.BuildTargets.NDependProject.xml"));
                doc = XDocument.Load(fxcpStream);
                doc.Save(buildRootDirectory + @"\BuildSettings\NDependProject.xml");

                ExtractResource("BuildConfigurator.BuildTargets.VersionIncrement.exe", buildRootDirectory + @"\BuildSettings\VersionIncrement.exe");


                ExtractResource("BuildConfigurator.BuildTargets.ScimitarPlugIn.exe", buildRootDirectory + @"\BuildSettings\ScimitarPlugIn.exe");

                //to load the Scimitar config file in the build settings folder
                fxcpStream = new StreamReader(asmbly.GetManifestResourceStream("BuildConfigurator.BuildTargets.ScimitarPlugIn.exe.config"));
                doc = XDocument.Load(fxcpStream);
                doc.Save(buildRootDirectory + @"\BuildSettings\ScimitarPlugIn.exe.config");                
                

            }

        }

        /// <summary>
        /// This method can retrieve all the configured
        /// project's configurations in a list.
        /// </summary>
        /// <returns>List of all the project configurations</returns>
        public static IList<string> GetProjectBuildConfigurations()
        {
            //test-aneesh
            //BuildConfigurator.AddProjectFolders("chummaProject");
            //test-aneesh

            IList<string> prjList = new List<string>();
            XDocument ccnetConfig = XDocument.Load(@"C:\Program Files\CruiseControl.NET\server\ccnet.config");
            IEnumerable<XElement> projects = ccnetConfig.Root.Elements();

            foreach (XElement project in projects)
            {
                prjList.Add(project.Element("name").Value);
                
            }
                return prjList;
        }

        public static BuildParameters GetProjectBuildConfiguration(string ccnetProjectName)
        {
            BuildParameters buildParameters = null;
            XDocument ccnetConfig = XDocument.Load(@"C:\Program Files\CruiseControl.NET\server\ccnet.config");
            IEnumerable<XElement> projects = ccnetConfig.Root.Elements();
			

            foreach (XElement project in projects)
            {
                if (project.Element("name").Value == ccnetProjectName)
                {
                    buildParameters = new BuildParameters();
                    buildParameters.GeneralSettings = new GeneralSettings();
                    buildParameters.GeneralSettings.CCnetProjectName = ccnetProjectName;
					//buildParameters.GeneralSettings.DevEnvPath = project.Element("DevEnvPath").Value;
					string trgpath = project.Element("tasks").Element("msbuild").Element("workingDirectory").Value;
					trgpath = trgpath.Substring(0, trgpath.LastIndexOf(@"\"));
					buildParameters.GeneralSettings.TargetPath = trgpath;

                    XElement sourceControl = project.Element("sourcecontrol");
                    if (sourceControl != null)
                    {
                        buildParameters.SourceControlSettings = new SourceControlSettings();
                        XAttribute attr = sourceControl.Attribute("type");
                        buildParameters.SourceControlSettings.SourceType = attr.Value;

                        switch (buildParameters.SourceControlSettings.SourceType)
                        {
                            case "svn":
                                buildParameters.SourceControlSettings.TrunkUrl = sourceControl.Element("trunkUrl").Value;
                                buildParameters.SourceControlSettings.UserName = sourceControl.Element("username").Value;
                                buildParameters.SourceControlSettings.Password = sourceControl.Element("password").Value;
                                buildParameters.SourceControlSettings.AutoGetSource = sourceControl.Element("autoGetSource").Value;
                                buildParameters.SourceControlSettings.TagOnSuccess = sourceControl.Element("tagOnSuccess").Value;
                                buildParameters.SourceControlSettings.TagBaseUrl = sourceControl.Element("tagBaseUrl").Value;
                                buildParameters.SourceControlSettings.Timeout = sourceControl.Element("timeout").Value;
                                break;
                            case "vsts":
                                buildParameters.SourceControlSettings.TrunkUrl = sourceControl.Element("server").Value;
                                buildParameters.SourceControlSettings.UserName = sourceControl.Element("username").Value;
                                buildParameters.SourceControlSettings.Password = sourceControl.Element("password").Value;
                                attr = sourceControl.Attribute("autoGetSource");
                                buildParameters.SourceControlSettings.AutoGetSource = attr.Value;
                                attr = sourceControl.Attribute("applyLabel");
                                buildParameters.SourceControlSettings.TagOnSuccess = attr.Value;
                                buildParameters.SourceControlSettings.Vstsproject = sourceControl.Element("project").Value;
                                break;
                            case "clearCase":
                                buildParameters.SourceControlSettings.CcViewPath = sourceControl.Element("viewPath").Value;
                                buildParameters.SourceControlSettings.CCBranch = sourceControl.Element("branch").Value;
                                buildParameters.SourceControlSettings.AutoGetSource = sourceControl.Element("autoGetSource").Value;
                                buildParameters.SourceControlSettings.TagOnSuccess = sourceControl.Element("useLabel").Value;
                                buildParameters.SourceControlSettings.IsCCBaseLine = sourceControl.Element("useBaseline").Value;
                                buildParameters.SourceControlSettings.CCProjectVob = sourceControl.Element("projectVobName").Value;
                                buildParameters.SourceControlSettings.CcViewName = sourceControl.Element("viewName").Value;
                                buildParameters.SourceControlSettings.Timeout = sourceControl.Element("timeout").Value;
                                break;
                            default:
                                break;

                        }
                    }

                    XElement triggers = project.Element("triggers");
                    buildParameters.TriggerSettings = new TriggerSettings();
                    buildParameters.ScheduleTriggerSetting = new ScheduleTriggerSetting();
                    buildParameters.FilterTriggerSetting = new FilterTriggerSetting();

                    if (triggers != null)
                    {
                        

                        XElement intervalTrigger = triggers.Element("intervalTrigger");
                        if (intervalTrigger != null)
                        {
                            buildParameters.TriggerSettings.TriggerInterval = intervalTrigger.Attribute("seconds").Value;
                            buildParameters.TriggerSettings.BuildCondition = intervalTrigger.Attribute("buildCondition").Value;
                            buildParameters.TriggerSettings.EnableTrigger = true;
                        }
                        else
                        {
                            buildParameters.TriggerSettings.TriggerInterval = string.Empty;
                            buildParameters.TriggerSettings.EnableTrigger = false;
                        }

                        XElement schTrigger = triggers.Element("scheduleTrigger");
                        {
                            if (schTrigger != null)
                            {
                                buildParameters.ScheduleTriggerSetting.EnablescheduleTrigger = true;
                                buildParameters.ScheduleTriggerSetting.BuildCondition = schTrigger.Attribute("buildCondition").Value;
                                buildParameters.ScheduleTriggerSetting.TriggerIntervalTime = schTrigger.Attribute("time").Value;

                                XElement wDays=schTrigger.Element("weekDays");

                                if (wDays != null)
                                {
                                    IEnumerable<XElement> weekdays = wDays.Elements("weekDay");
                                    string _weekdats = string.Empty;
                                    foreach (XElement weekday in weekdays)
                                    {
                                        _weekdats = _weekdats + weekday.Value + ";";
                                    }
                                    buildParameters.ScheduleTriggerSetting.WeekDays = _weekdats;
                                }
                            }
                            else
                            {
                                buildParameters.ScheduleTriggerSetting.EnablescheduleTrigger = false;
                                buildParameters.ScheduleTriggerSetting.BuildCondition = string.Empty;
                                buildParameters.ScheduleTriggerSetting.TriggerIntervalTime = string.Empty;
                                buildParameters.ScheduleTriggerSetting.WeekDays = string.Empty;

                            }
                        }
                        XElement filtrigger = triggers.Element("filterTrigger");
                        {
                            if (filtrigger != null)
                            {
                                buildParameters.FilterTriggerSetting.EnableFilterTrigger = true;
                                buildParameters.FilterTriggerSetting.DuratinoSecs = filtrigger.Element("trigger").Attribute("seconds").Value;
                                buildParameters.FilterTriggerSetting.EndTime = filtrigger.Attribute("endTime").Value;
                                buildParameters.FilterTriggerSetting.StartTime = filtrigger.Attribute("startTime").Value; 
                            }
                            else
                            {
                                buildParameters.FilterTriggerSetting.EnableFilterTrigger = false;
                                buildParameters.FilterTriggerSetting.DuratinoSecs = string.Empty;
                                buildParameters.FilterTriggerSetting.EndTime = string.Empty;
                                buildParameters.FilterTriggerSetting.StartTime = string.Empty; 
                            }
                        }
                    }

                    XElement tasks = project.Element("tasks");
                    buildParameters.CompileSettings = new CompileSettings();
					buildParameters.CompileSettings.CheckinWaitingTime = project.Element("modificationDelaySeconds").Value;
                    if (tasks != null)
                    {
                        XElement msbuild = tasks.Element("msbuild");
                        if (msbuild != null)
                        {
                            buildParameters.CompileSettings.BuildTimeout = msbuild.Element("timeout").Value;
                        }

                        buildParameters.EmailSettings = new EmailSettings();
                        XElement publishers = project.Element("publishers");
                        XElement emailtasks = publishers.Element("email");
                        if (emailtasks != null)
                        {
                            buildParameters.EmailSettings.EnableEmail = true;
                            //buildParameters.EmailSettings.Body = emailtasks.Elements    
                            buildParameters.EmailSettings.FromAddresses = emailtasks.Attribute("from").Value;
                            buildParameters.EmailSettings.SmtpServer = emailtasks.Attribute("mailhost").Value;

                            XElement Users = emailtasks.Element("users");

                            IEnumerable<XElement> usersList = Users.Elements("user");
                            foreach (XElement usr in usersList)
                            {
                                buildParameters.EmailSettings.ToAddresses = buildParameters.EmailSettings.ToAddresses + usr.Attribute("address").Value + ";";
                            }

                        }

                    }

                    

                    string buildScriptFile =  buildParameters.GeneralSettings.TargetPath + @"\Buildroot_" + ccnetProjectName + @"\build.proj";
					
					
                    XDocument buildConfig = XDocument.Load(buildScriptFile);
					buildParameters.PostScriptSettings = new PostScriptSettings();
                    XNamespace defaultns = "http://schemas.microsoft.com/developer/msbuild/2003";
                    IEnumerable<XElement> propertyGroups = buildConfig.Root.Elements(defaultns + "PropertyGroup");

					

					foreach (XElement propertyGroup in propertyGroups)
                    {
                        if (((XElement)propertyGroup.FirstNode).Name == defaultns + "Common")
                        {
                            buildParameters.CompileSettings.BuildConfiguration = propertyGroup.Element(defaultns + "BuildConfiguration").Value;
                            buildParameters.CompileSettings.SolutionFile = propertyGroup.Element(defaultns + "MainSolutionFile").Value;
							buildParameters.GeneralSettings.DevEnvPath = propertyGroup.Element(defaultns + "DevEnvPath").Value;
                        }
                        else if (((XElement)propertyGroup.FirstNode).Name == defaultns + "PreScript")
                        {
                            buildParameters.PreScriptSettings = new PreScriptSettings();
                            if (propertyGroup.Element(defaultns + "EnablePreScriptTask").Value.ToUpper(CultureInfo.InvariantCulture) == "TRUE")
                            {
                                buildParameters.PreScriptSettings.EnablePreScript = true;
                                buildParameters.PreScriptSettings.PreScriptFile = propertyGroup.Element(defaultns + "PreScriptFile").Value;
                            }
                            else
                            {
                                buildParameters.PreScriptSettings.EnablePreScript = false;
                            }
                        }
                        else if (((XElement)propertyGroup.FirstNode).Name == defaultns + "Version")
                        {
                            buildParameters.VersioningSettings = new VersioningSettings();
                            if (propertyGroup.Element(defaultns + "EnableVersionTask").Value.ToUpper(CultureInfo.InvariantCulture) == "TRUE")
                            {
                                buildParameters.VersioningSettings.EnableVersion = true;
                                buildParameters.VersioningSettings.MajorVersion = propertyGroup.Element(defaultns + "Major").Value;
                                buildParameters.VersioningSettings.MinorVersion = propertyGroup.Element(defaultns + "Minor").Value;
                                buildParameters.VersioningSettings.Build = propertyGroup.Element(defaultns + "Build").Value;
                                buildParameters.VersioningSettings.Revision = propertyGroup.Element(defaultns + "Revision").Value;
                            }
                            else
                            {
                                buildParameters.VersioningSettings.EnableVersion = false;
                            }
                        }
                        else if (((XElement)propertyGroup.FirstNode).Name == defaultns + "StyleCop")
                        {
                            buildParameters.StyleCopSettings = new StyleCopSettings();
                            if (propertyGroup.Element(defaultns + "EnableStyleCopTask").Value.ToUpper(CultureInfo.InvariantCulture) == "TRUE")
                            {
                                buildParameters.StyleCopSettings.EnableStyleCop = true;
                                buildParameters.StyleCopSettings.StyleCopCustomSettingsFile = propertyGroup.Element(defaultns + "StyleCopCustomSettingsFile").Value;
                            }
                            else
                            {
                                buildParameters.StyleCopSettings.EnableStyleCop = false;
                            }
                        }
                        else if (((XElement)propertyGroup.FirstNode).Name == defaultns + "NUnit")
                        {
                            buildParameters.NUnitSettings = new NUnitSettings();
                            if (propertyGroup.Element(defaultns + "EnableNUnitTask").Value.ToUpper(CultureInfo.InvariantCulture) == "TRUE")
                            {
                                buildParameters.NUnitSettings.EnableNUnit = true;
                                buildParameters.NUnitSettings.NUnitEXEPath = propertyGroup.Element(defaultns + "NUnitInstallDirectory").Value; 
                                buildParameters.NUnitSettings.NUnitReportFile = propertyGroup.Element(defaultns + "NUnitReportFile").Value;
                                buildParameters.NUnitSettings.NUnitDLLName = propertyGroup.Element(defaultns + "NUnitDLLName").Value; 
                                
                            }
                            else
                            {
                                buildParameters.NUnitSettings.EnableNUnit = false;
                            }
                        }
						else if (((XElement)propertyGroup.FirstNode).Name == defaultns + "MSTest")
						{
							buildParameters.MSTestSettings = new MstestSettings();
							if (propertyGroup.Element(defaultns + "EnableMstestTask").Value.ToUpper(CultureInfo.InvariantCulture) == "TRUE")
							{
								buildParameters.MSTestSettings.EnableMstestTask= true;
								buildParameters.MSTestSettings.MstestExe = propertyGroup.Element(defaultns + "MStestExe").Value;
								buildParameters.MSTestSettings.MstestDll = propertyGroup.Element(defaultns + "MSTestDll").Value;
								buildParameters.MSTestSettings.Mstestoutput = propertyGroup.Element(defaultns + "MSTestOutPut").Value;								
							}
							else
							{
								buildParameters.MSTestSettings.EnableMstestTask = false;
							}
						}
                        else if (((XElement)propertyGroup.FirstNode).Name == defaultns + "NCover")
                        {
                            buildParameters.NCoverSettings = new NCoverSettings();
                            if (propertyGroup.Element(defaultns + "EnableNCoverTask").Value.ToUpper(CultureInfo.InvariantCulture) == "TRUE")
                            {
                                buildParameters.NCoverSettings.EnableNCover = true;
                                buildParameters.NCoverSettings.NCoverLogFile = propertyGroup.Element(defaultns + "CoverageLogFile").Value;
                            }
                            else
                            {
                                buildParameters.NCoverSettings.EnableNCover = false;
                            }
                        }
                        else if (((XElement)propertyGroup.FirstNode).Name == defaultns + "MSCodeCoverage")
                        {
                            buildParameters.MSCodeCoverageSettings = new MSCodeCoverageSettings();
                            if (propertyGroup.Element(defaultns + "EnableMSCodeCoverage").Value.ToUpper(CultureInfo.InvariantCulture) == "TRUE")
                            {
                                buildParameters.MSCodeCoverageSettings.EnableMSCodeCoverage = true;
                                buildParameters.MSCodeCoverageSettings.InstrExePath = propertyGroup.Element(defaultns + "InstrExePath").Value;
                                buildParameters.MSCodeCoverageSettings.PerfCmdExePath = propertyGroup.Element(defaultns + "PerfCmdExePath").Value;
                                buildParameters.MSCodeCoverageSettings.MsTestExePath = propertyGroup.Element(defaultns + "MStestExePath").Value;
                                buildParameters.MSCodeCoverageSettings.InstrBinaries = propertyGroup.Element(defaultns + "Instrbinaries").Value;
                                buildParameters.MSCodeCoverageSettings.TestBinary = propertyGroup.Element(defaultns + "TestBinary").Value;
                                buildParameters.MSCodeCoverageSettings.CoverageOutputFile = propertyGroup.Element(defaultns + "outputCoverageFileName").Value;
                                buildParameters.MSCodeCoverageSettings.MscovRepLink = propertyGroup.Element(defaultns + "MSCoverageLink").Value;
                            }
                            else
                            {
                                buildParameters.MSCodeCoverageSettings.EnableMSCodeCoverage = false;
                            }
                        }
                        else if (((XElement)propertyGroup.FirstNode).Name == defaultns + "FxCop")
                        {
                            buildParameters.FxCopSettings = new FxCopSettings();
                            if (propertyGroup.Element(defaultns + "EnableFxCopTask").Value.ToUpper(CultureInfo.InvariantCulture) == "TRUE")
                            {
                                buildParameters.FxCopSettings.EnableFxCop = true;
                                buildParameters.FxCopSettings.FxCopReportFile = propertyGroup.Element(defaultns + "FxCopResultsFile").Value;
                                buildParameters.FxCopSettings.FxCopProjectFile = propertyGroup.Element(defaultns + "FxCopProjectFile").Value;
                            }
                            else
                            {
                                buildParameters.FxCopSettings.EnableFxCop = false;
                            }
                        }

                        else if (((XElement)propertyGroup.FirstNode).Name == defaultns + "CatNet")
                        {
                            buildParameters.CatNetSettings = new CatNetSettings();
                            if (propertyGroup.Element(defaultns + "EnableCatNet").Value.ToUpper(CultureInfo.InvariantCulture) == "TRUE")
                            {
                                buildParameters.CatNetSettings.EnableCatNet = true;
                                buildParameters.CatNetSettings.ScanFiles = propertyGroup.Element(defaultns + "ScanFiles").Value;
                                buildParameters.CatNetSettings.CNPath = propertyGroup.Element(defaultns + "CNPath").Value;
                                buildParameters.CatNetSettings.CNRptFileName = propertyGroup.Element(defaultns + "CNRptFileName").Value;
                            }
                            else
                            {
                                buildParameters.CatNetSettings.EnableCatNet = false;
                            }
                        }


                        else if (((XElement)propertyGroup.FirstNode).Name == defaultns + "SandCastleHFB")
                        {
                            buildParameters.SandcastleHelpFileBuilderSettings = new SandcastleHelpFileBuilderSettings();
                            if (propertyGroup.Element(defaultns + "EnableSandCastleHFBTask").Value.ToUpper(CultureInfo.InvariantCulture) == "TRUE")
                            {
                                buildParameters.SandcastleHelpFileBuilderSettings.EnableSandcastleHelpFileBuilder = true;
                                buildParameters.SandcastleHelpFileBuilderSettings.SandcastleHelpFileBuilderProjectFile = propertyGroup.Element(defaultns + "SandCastleHFBProject").Value;
                                buildParameters.SandcastleHelpFileBuilderSettings.SandcastleHelpFileBuilderOutputDirectory = propertyGroup.Element(defaultns + "SandCastleOutputFolderName").Value;
                            }
                            else
                            {
                                buildParameters.SandcastleHelpFileBuilderSettings.EnableSandcastleHelpFileBuilder = false;
                            }
                        }
                        else if (((XElement)propertyGroup.FirstNode).Name == defaultns + "NDepend")
                        {
                            buildParameters.NDependSettings = new NDependSettings();
                            if (propertyGroup.Element(defaultns + "EnableNDependTask").Value.ToUpper(CultureInfo.InvariantCulture) == "TRUE")
                            {
                                buildParameters.NDependSettings.EnableNDepend = true;
                                buildParameters.NDependSettings.NDependProjectFile = propertyGroup.Element(defaultns + "NDependProjectFile").Value;
                                buildParameters.NDependSettings.NDependReportDirectory = propertyGroup.Element(defaultns + "NDependReportDirectory").Value;
                            }
                            else
                            {
                                buildParameters.NDependSettings.EnableNDepend = false;
                            }
                        }
                        else if (((XElement)propertyGroup.FirstNode).Name == defaultns + "Database")
                        {
                            buildParameters.DatabaseSettings = new DatabaseSettings();
                            if (propertyGroup.Element(defaultns + "EnableDatabaseTask").Value.ToUpper(CultureInfo.InvariantCulture) == "TRUE")
                            {
                                buildParameters.DatabaseSettings.EnableDatabase = true;
                                buildParameters.DatabaseSettings.DBServerName = propertyGroup.Element(defaultns + "dbserver").Value;
                                buildParameters.DatabaseSettings.DBLogin = propertyGroup.Element(defaultns + "dbuser").Value;
                                buildParameters.DatabaseSettings.DBPassword = propertyGroup.Element(defaultns + "dbpassword").Value;
                                buildParameters.DatabaseSettings.DBName = propertyGroup.Element(defaultns + "dbname").Value;
                            }
                            else
                            {
                                buildParameters.DatabaseSettings.EnableDatabase = false;
                            }
                        }
                        //else if (((XElement)propertyGroup.FirstNode).Name == defaultns + "Email")
                        //{
                        //    buildParameters.EmailSettings = new EmailSettings();
                        //    if (propertyGroup.Element(defaultns + "EnableEmailTask").Value.ToUpper(CultureInfo.InvariantCulture) == "TRUE")
                        //    {
                        //        //buildParameters.EmailSettings.EnableEmail = true;
                        //        //buildParameters.EmailSettings.SmtpServer = propertyGroup.Element(defaultns + "SmtpServer").Value;
                        //        //buildParameters.EmailSettings.ToAddresses = propertyGroup.Element(defaultns + "ToAddresses").Value;
                        //        //buildParameters.EmailSettings.FromAddresses = propertyGroup.Element(defaultns + "FromAddresses").Value;
                        //        //buildParameters.EmailSettings.Subject = propertyGroup.Element(defaultns + "Subject").Value;
                        //        //buildParameters.EmailSettings.Body = propertyGroup.Element(defaultns + "Body").Value;
                        //    }
                        //    else
                        //    {
                        //        //buildParameters.EmailSettings.EnableEmail = false;
                        //    }
                        //}
                        else if (((XElement)propertyGroup.FirstNode).Name == defaultns + "PostScript")
                        {

                            if (propertyGroup.Element(defaultns + "EnablePostScriptTask").Value.ToUpper(CultureInfo.InvariantCulture) == "TRUE")
                            {
                                buildParameters.PostScriptSettings.EnablePostScript = true;
                                buildParameters.PostScriptSettings.PostScriptFile = propertyGroup.Element(defaultns + "PostScriptFile").Value;
                            }
                            else
                            {
                                buildParameters.PostScriptSettings.EnablePostScript = false;
                            }
                        }
                        else if (((XElement)propertyGroup.FirstNode).Name == defaultns + "PostCompile")
                        {

                            if (propertyGroup.Element(defaultns + "EnablePostCompile").Value.ToUpper(CultureInfo.InvariantCulture) == "TRUE")
                            {
                                buildParameters.PostScriptSettings.EnablePostCompile = true;
                                buildParameters.PostScriptSettings.PostCompileScriptFile = propertyGroup.Element(defaultns + "PostCompileFile").Value;
                            }
                            else
                            {
                                buildParameters.PostScriptSettings.EnablePostCompile = false;
                            }
                        }
                        else if (((XElement)propertyGroup.FirstNode).Name == defaultns + "PostDeploy")
                        {

                            if (propertyGroup.Element(defaultns + "EnablePostDeploy").Value.ToUpper(CultureInfo.InvariantCulture) == "TRUE")
                            {
                                buildParameters.PostScriptSettings.EnablePostDeploy = true;
                                buildParameters.PostScriptSettings.PostDeployScriptFile = propertyGroup.Element(defaultns + "PostDeployFile").Value;
                            }
                            else
                            {
                                buildParameters.PostScriptSettings.EnablePostDeploy = false;
                            }
                        }
                        else if (((XElement)propertyGroup.FirstNode).Name == defaultns + "IISConfig")
                        {
                            buildParameters.IISSettings = new IISSettings();

                            if (propertyGroup.Element(defaultns + "EnableIIS").Value.ToUpper(CultureInfo.InvariantCulture) == "TRUE")
                            {
                                buildParameters.IISSettings.EnableIIS = true;
                                buildParameters.IISSettings.ApplicationPoolName = propertyGroup.Element(defaultns + "AppPoolName").Value;
                                buildParameters.IISSettings.IISType = propertyGroup.Element(defaultns + "IISType").Value;
                                buildParameters.IISSettings.PhysicalDirectoryPath = propertyGroup.Element(defaultns + "VdirPhyPath").Value;
                                buildParameters.IISSettings.VirtualDirectoryName = propertyGroup.Element(defaultns + "VdirName").Value;
                                buildParameters.IISSettings.WebProjectPath = propertyGroup.Element(defaultns + "WebProjLocation").Value;
                                buildParameters.IISSettings.WebServerName = propertyGroup.Element(defaultns + "Server").Value;
                                buildParameters.IISSettings.DevelopmentServerLocation = propertyGroup.Element(defaultns + "DevDeployLoc").Value;
                                buildParameters.IISSettings.QAServerLocation = propertyGroup.Element(defaultns + "QADeployLoc").Value;
                                buildParameters.IISSettings.ProductionServerLocation = propertyGroup.Element(defaultns + "ProdDeployLoc").Value;

                            }
                            else
                            {
                                buildParameters.IISSettings.EnableIIS = false;
                            }
                        }

                    }
                }
            }
			GetTargetDependants(buildParameters);
            return buildParameters;
        }

		public static void UpdateTargetDependants(BuildParameters buildParameters)
		{
			XDocument prjFile = XDocument.Load(buildParameters.GeneralSettings.TargetPath + @"\Buildroot_" + buildParameters.GeneralSettings.CCnetProjectName + @"\build.proj");
			IEnumerable<XElement> targets = prjFile.Root.Elements();
			foreach (XElement target in targets)
			{
				try
				{
					if (target.Attribute("Name").Value == "UnitTest")
					{
						if (!string.IsNullOrEmpty(buildParameters.NUnitSettings.NUnitDependants))
						{
							XAttribute attr = new XAttribute("DependsOnTargets", buildParameters.NUnitSettings.NUnitDependants);
							target.Add(attr);
						}
					}
					if (target.Attribute("Name").Value == "Mstest")
					{
						if (!string.IsNullOrEmpty(buildParameters.MSTestSettings.MsTestDependants))
						{
							XAttribute attr = new XAttribute("DependsOnTargets", buildParameters.MSTestSettings.MsTestDependants);
							target.Add(attr);
						}
					}


					if (target.Attribute("Name").Value == "Coverage")
					{
						if (!string.IsNullOrEmpty(buildParameters.NCoverSettings.NCoverDependants))
						{
							XAttribute attr = new XAttribute("DependsOnTargets", buildParameters.NCoverSettings.NCoverDependants);
							target.Add(attr);
						}
					}

					if (target.Attribute("Name").Value == "Reporting")
					{
						if (!string.IsNullOrEmpty(buildParameters.FxCopSettings.FxCopDependants))
						{
							XAttribute attr = new XAttribute("DependsOnTargets", buildParameters.FxCopSettings.FxCopDependants);
							target.Add(attr);
						}
					}

					if (target.Attribute("Name").Value == "SandcastleHelpFileBuilder")
					{
						if (!string.IsNullOrEmpty(buildParameters.SandcastleHelpFileBuilderSettings.SHFBDependants))
						{
							XAttribute attr = new XAttribute("DependsOnTargets", buildParameters.SandcastleHelpFileBuilderSettings.SHFBDependants);
							target.Add(attr);
						}
					}

					if (target.Attribute("Name").Value == "NDepend")
					{
						if (!string.IsNullOrEmpty(buildParameters.NDependSettings.NDependDependants))
						{
							XAttribute attr = new XAttribute("DependsOnTargets", buildParameters.NDependSettings.NDependDependants);
							target.Add(attr);
						}
					}
					if (target.Attribute("Name").Value == "Database")
					{
						if (!string.IsNullOrEmpty(buildParameters.DatabaseSettings.DBDependants))
						{
							XAttribute attr = new XAttribute("DependsOnTargets", buildParameters.DatabaseSettings.DBDependants);
							target.Add(attr);
						}
					}
					if (target.Attribute("Name").Value == "Database")
					{
						if (!string.IsNullOrEmpty(buildParameters.DatabaseSettings.DBDependants))
						{
							XAttribute attr = new XAttribute("DependsOnTargets", buildParameters.DatabaseSettings.DBDependants);
							target.Add(attr);
						}
					}
					if (target.Attribute("Name").Value == "IIS6Task")
					{
						if (!string.IsNullOrEmpty(buildParameters.IISSettings.IISDependants))
						{
							XAttribute attr = new XAttribute("DependsOnTargets", buildParameters.IISSettings.IISDependants);
							target.Add(attr);
						}
					}
					if (target.Attribute("Name").Value == "IIS7Task")
					{
						if (!string.IsNullOrEmpty(buildParameters.IISSettings.IISDependants))
						{
							XAttribute attr = new XAttribute("DependsOnTargets", buildParameters.IISSettings.IISDependants);
							target.Add(attr);
						}
					}
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex.Message);
				}
			}

			prjFile.Save(buildParameters.GeneralSettings.TargetPath + @"\Buildroot_" + buildParameters.GeneralSettings.CCnetProjectName + @"\build.proj");
		}

		public static BuildParameters GetTargetDependants(BuildParameters buildParameters)
		{
			XDocument prjFile = XDocument.Load(buildParameters.GeneralSettings.TargetPath + @"\Buildroot_" + buildParameters.GeneralSettings.CCnetProjectName + @"\build.proj");

			IEnumerable<XElement> targets = prjFile.Root.Elements();
			foreach (XElement target in targets)
			{
				try
				{
					if (target.Attribute("Name").Value == "UnitTest")
					{
						buildParameters.NUnitSettings.NUnitDependants  = target.Attribute("DependsOnTargets").Value;
					}
					if (target.Attribute("Name").Value == "Mstest")
					{
						buildParameters.MSTestSettings.MsTestDependants = target.Attribute("DependsOnTargets").Value;
					}
					if (target.Attribute("Name").Value == "Coverage")
					{
						buildParameters.NCoverSettings.NCoverDependants = target.Attribute("DependsOnTargets").Value;
					}
					if (target.Attribute("Name").Value == "Reporting")
					{
						buildParameters.FxCopSettings.FxCopDependants = target.Attribute("DependsOnTargets").Value;
					}
					if (target.Attribute("Name").Value == "Reporting")
					{
						buildParameters.FxCopSettings.FxCopDependants = target.Attribute("DependsOnTargets").Value;
					}
					if (target.Attribute("Name").Value == "SandcastleHelpFileBuilder")
					{
						buildParameters.SandcastleHelpFileBuilderSettings.SHFBDependants  = target.Attribute("DependsOnTargets").Value;
					}
					if (target.Attribute("Name").Value == "NDepend")
					{
						buildParameters.NDependSettings.NDependDependants = target.Attribute("DependsOnTargets").Value;
					}
					if (target.Attribute("Name").Value == "Database")
					{
						buildParameters.DatabaseSettings.DBDependants = target.Attribute("DependsOnTargets").Value;
					}
					if (target.Attribute("Name").Value == "IIS6Task")
					{
						buildParameters.IISSettings.IISDependants = target.Attribute("DependsOnTargets").Value;
					}
					if (target.Attribute("Name").Value == "IIS7Task")
					{
						buildParameters.IISSettings.IISDependants = target.Attribute("DependsOnTargets").Value;
					}
					  
				}
				catch (Exception ex)
				{
				}
			}
			return buildParameters;
		}

        
        public static void MSCovScriptCreation(string parentFolder, MSCodeCoverageSettings mscodecovset)
        {
            fI = new FileInfo(parentFolder + "\\mscodecov.bat");
            oDDF = fI.CreateText();
            oDDF.WriteLine("\"" + mscodecovset.PerfCmdExePath + "\" /start:coverage /output:" + mscodecovset.CoverageOutputFile );
            oDDF.WriteLine("\"" + mscodecovset.MsTestExePath + "\" /testcontainer:" + mscodecovset.TestBinary);
            oDDF.WriteLine("\"" + mscodecovset.PerfCmdExePath + "\" /shutdown");
            oDDF.Close();
        }



		

		

        static void ExtractResource(string resource, string path)
        {
            Assembly asmbly = Assembly.GetExecutingAssembly();
            Stream stream = asmbly.GetManifestResourceStream(resource);
            byte[] bytes = new byte[(int)stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            File.WriteAllBytes(path, bytes);
        }

        #region CCNet Dashboard Configuration

        static bool nunit, fxcop, ncover, mstest;
        public static void UpdateCCNetDashboard()
        {
            GetProjectConfigDetails();
            XDocument doc = XDocument.Load(@"C:\Program Files\CruiseControl.NET\webdashboard\dashboard.config");
            doc.Descendants("xslFile").Remove();
            doc.Descendants("xslReportBuildPlugin").Remove();

            IEnumerable<XElement> _xslFileNames = doc.Root.Descendants("xslFileNames");
            IEnumerable<XElement> _buildPlugins = doc.Root.Descendants("buildPlugins");
            
            #region Contains Build Plugins

            XElement _nunitPlugIn = new XElement("xslReportBuildPlugin",
                  new XAttribute("description", "NUnit Details"),
                  new XAttribute("actionName", "NUnitDetailsBuildReport"),
                  new XAttribute("xslFileName", @"xsl\tests.xsl"));

            XElement _nunitTimingPlugIn = new XElement("xslReportBuildPlugin",
                new XAttribute("description", "NUnit Timings"),
                new XAttribute("actionName", "NUnitTimingsBuildReport"),
                new XAttribute("xslFileName", @"xsl\timing.xsl"));

            XElement _fxcopPlugIn = new XElement("xslReportBuildPlugin",
                new XAttribute("description", "FxCop Report"),
                new XAttribute("actionName", "FxCopBuildReport"),
                new XAttribute("xslFileName", @"xsl\FxCopReport.xsl"));

            XElement _ncoverPlugIn = new XElement("xslReportBuildPlugin",
                new XAttribute("description", "NCover Report"),
                new XAttribute("actionName", "NCoverBuildReport"),
                new XAttribute("xslFileName", @"xsl\NCover.xsl"));

            XElement _mstestPlugIn = new XElement("xslReportBuildPlugin",
                new XAttribute("description", "MsTest Report"),
                new XAttribute("actionName", "MsTestReport"),
                new XAttribute("xslFileName", @"xsl\MsTestReport2008.xsl"));

            #endregion

            foreach (XElement ele in _xslFileNames)
            {
                XElement _header = new XElement("xslFile", @"xsl\header.xsl");
                ele.Add(_header);
                _header = new XElement("xslFile", @"xsl\modifications.xsl");
                ele.Add(_header);
                _header = new XElement("xslFile", @"xsl\compile.xsl");
                ele.Add(_header);
                _header = null;

                XElement _unittest;
                if (nunit)
                {
                    _unittest = new XElement("xslFile", @"xsl\unittests.xsl");
                    ele.Add(_unittest);
                    _unittest = null;
                }

                if (mstest)
                {
                    _unittest = new XElement("xslFile", @"xsl\MsTestSummary2008.xsl");
                    ele.Add(_unittest);
                    _unittest = null;
                }

                if (fxcop)
                {
                    _unittest = new XElement("xslFile", @"xsl\fxcop-summary.xsl");
                    ele.Add(_unittest);
                    _unittest = null;
                }

                if (ncover)
                {
                    _unittest = new XElement("xslFile", @"xsl\NCoverSummary.xsl");
                    ele.Add(_unittest);
                    _unittest = null;
                }

            }

            foreach (XElement ele in _buildPlugins)
            {
                if (nunit)
                {
                    ele.Add(_nunitPlugIn);
                    ele.Add(_nunitTimingPlugIn);
                }
                if (fxcop)
                {
                    ele.Add(_fxcopPlugIn);
                }
                if (ncover)
                {
                    ele.Add(_ncoverPlugIn);
                }
                if (mstest)
                {
                    ele.Add(_mstestPlugIn);
                }
            }
            doc.Save(@"C:\Program Files\CruiseControl.NET\webdashboard\dashboard.config");

        }

        private static void GetProjectConfigDetails()
        {
            XDocument doc = XDocument.Load(@"C:\Program Files\CruiseControl.NET\server\ccnet.config");
            if (doc != null)
            {


                IEnumerable<XElement> msbuildele = doc.Descendants("msbuild");
                IEnumerable<XElement> workingDirs = msbuildele.Descendants("workingDirectory");

                foreach (XElement wrkDir in workingDirs)
                {
                    XNamespace defaultns = "http://schemas.microsoft.com/developer/msbuild/2003";
                    XDocument _docBuildproj = XDocument.Load(wrkDir.Value + "\\build.proj");
                    IEnumerable<XElement> _properties = _docBuildproj.Descendants(defaultns + "PropertyGroup");

                    IEnumerable<XElement> _nunitElement = _properties.Descendants(defaultns + "EnableNUnitTask");
                    IEnumerable<XElement> _ncoverElement = _properties.Descendants(defaultns + "EnableNCoverTask");
                    IEnumerable<XElement> _fxCopElement = _properties.Descendants(defaultns + "EnableFxCopTask");
                    IEnumerable<XElement> _mstestElement = _properties.Descendants(defaultns + "EnableMstestTask");




                    foreach (XElement ele in _nunitElement)
                    {
                        if (!nunit)
                        {
                            nunit = Convert.ToBoolean(ele.Value);
                        }

                    }

                    foreach (XElement ele in _ncoverElement)
                    {
                        if (!ncover)
                        {
                            ncover = Convert.ToBoolean(ele.Value);
                        }

                    }

                    foreach (XElement ele in _fxCopElement)
                    {
                        if (!fxcop)
                        {
                            fxcop = Convert.ToBoolean(ele.Value);
                        }

                    }

                    foreach (XElement ele in _mstestElement)
                    {
                        if (!mstest)
                        {
                            mstest = Convert.ToBoolean(ele.Value);
                        }

                    }



                }

                msbuildele = null;
                workingDirs = null;
            }



            doc = null;

        }

        #endregion

    }
}